<!-- 损耗设置 -->
<template>
    <div class="addMask">
        <el-dialog v-model="open" title="损耗设置" width="800" :close-on-click-modal="false">
            <div class="loss-setting-container">
                <div class="table-container">
                    <el-table :data="lossData" border style="width: 100%">

                        <el-table-column prop="spu_name" label="耗材名称" width="auto">
                            <template #default="scope">
                                <el-select v-model="scope.row.spu_id" placeholder="请选择" style="width: 100%" 
                                          @change="(value) => handleSpuChange(scope.row, value)">
                                    <el-option v-for="product in productOptions" :key="product.id"
                                        :label="product.name" :value="product.id">
                                    </el-option>
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column prop="consume_num" label="损耗设置" width="auto">
                            <template #default="scope">
                                <div class="loss-input-group">
                                 
                                    <el-input v-model.number="scope.row.consume_num" type="number" :min="0" size="small"
                                        style="width: 180px; text-align: center;" />
                                   
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="measure_unit_id" label="损耗单位" width="auto">
                            <template #default="scope">
                              <!-- 显示选中产品SPU对应的损耗单位 -->
                               <el-input v-model="scope.row.measure_unit_name" placeholder="请先选择耗材" 
                                        style="width: 100%" readonly />
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="100" align="center">
                            <template #default="scope">
                                <el-button type="danger" link @click="removeLossItem(scope.row)">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="add-item-container">
                        <el-button type="primary" link @click="addLossItem">+添加项</el-button>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import api from '@/api';

// 定义产品SPU接口
interface ProductSpu {
    id: number;
    name: string;
    measure_unit_id: number;
    measure_unit_name: string;
}

// 定义损耗设置项接口
interface LossItem {
    id?: number;
    warehouse_serve_id?: number;
    spu_id?: number;
    spu_name?: string;
    measure_unit_id?: number;
    consume_num: number;
    created_at?: string;
    updated_at?: string;
    measure_unit?: {
        id: number;
        name: string;
    };
    measure_unit_name?: string; // 用于显示的单位名称
}

const emit = defineEmits(['init']);

// 弹窗控制
const open = ref<boolean>(false);

// 损耗设置数据
const lossData = ref<LossItem[]>([]);

// 获取损耗设置列表
const getLossSettingList = async () => {
    const res = await api.consumablesSettings.getconsumablesSettingsList(
        {
            warehouse_id: String(warehouseId.value),
            service_id: String(warehouseServeId.value),
        }
    );
    if (res.code == 200) {
        lossData.value = res.data.data;
        
        // 初始化时，将measure_unit.name赋值给measure_unit_name用于显示
        lossData.value.forEach(item => {
            if (item.measure_unit?.name && !item.measure_unit_name) {
                item.measure_unit_name = item.measure_unit.name;
            }
        });
        
        console.log('损耗设置列表数据:', lossData.value);
    }
}

// 产品选项
const productOptions = ref<ProductSpu[]>([]);

// 获取产品spu下拉列表
const getProductList = async () => {
    const res = await api.publicFun.getProductSpuList({});
    if (res.code == 200) {
        productOptions.value = res.data;
        console.log('产品SPU列表数据:', productOptions.value);
    }
}

// 处理SPU选择变化
const handleSpuChange = (row: LossItem, spuId: number) => {
    console.log('SPU选择变化，当前行:', row, '选中ID:', spuId);
    
    // 根据选中的SPU ID找到对应的产品信息
    const selectedProduct = productOptions.value.find(product => product.id === spuId);
    
    if (selectedProduct) {
        // 直接更新当前行的SPU相关信息
        row.spu_id = selectedProduct.id;
        row.spu_name = selectedProduct.name;
        
        // 自动更新对应行的损耗单位信息
        row.measure_unit_id = selectedProduct.measure_unit_id;
        row.measure_unit_name = selectedProduct.measure_unit_name;
        
        console.log('自动更新损耗单位:', {
            spu_id: selectedProduct.id,
            spu_name: selectedProduct.name,
            measure_unit_id: selectedProduct.measure_unit_id,
            measure_unit_name: selectedProduct.measure_unit_name
        });
    } else {
        // 如果没找到对应产品，清空相关信息
        row.spu_id = undefined;
        row.spu_name = '';
        row.measure_unit_id = undefined;
        row.measure_unit_name = '';
        console.log('未找到对应产品，清空相关信息');
    }
};


// 添加损耗项
const addLossItem = () => {
    const newItem: LossItem = {
        // 生成一个临时的唯一ID用于新增项
        id: Date.now(), // 使用时间戳作为临时ID
        spu_id: undefined,
        consume_num: 0,
        measure_unit_id: undefined,
        measure_unit_name: '',
        warehouse_serve_id: warehouseServeId.value,
    };
    lossData.value.push(newItem);
    console.log('添加新的损耗项:', newItem);
};

// 移除损耗项
const removeLossItem = async (row: LossItem) => {
    // 如果是新增项（没有id），直接从数组中移除
    if (!row.id || row.id > 1000000000000) { // 时间戳生成的临时ID通常很大
        const index = lossData.value.findIndex(item => item === row);
        if (index > -1) {
            lossData.value.splice(index, 1);
            console.log('移除新增项，索引:', index);
        }
        return;
    }

    // 如果是已保存的项目，需要调用删除接口
    try {
        const confirm = await ElMessageBox.confirm('确定删除该损耗设置吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        });

        if (confirm) {
            console.log('删除损耗设置，ID:', row.id);
            
            // 将ID数组转换为JSON字符串格式
            const idsJsonString = JSON.stringify([row.id]);
            console.log('删除参数 ids:', idsJsonString);

            const res = await api.consumablesSettings.deleteconsumablesSettings({
                ids: idsJsonString
            });

            if (res.code == 200) {
                ElMessage.success('损耗设置删除成功');
                getLossSettingList(); // 刷新列表
            } else {
                ElMessage.error(res.message || '删除失败，请重试');
            }
        }
    } catch (error) {
        console.log('用户取消删除或删除失败:', error);
    }
};

// 取消操作
const handleCancel = () => {
    open.value = false;
};
const warehouseServeId = ref<number>(0); //仓库服务id为了知道我是在哪个仓库服务上设置
let warehouseName = ref<string>('');
let warehouseId = ref<number>(0);
// 打开弹窗
const openDialog = (item: any) => {
    if(item){
        warehouseServeId.value = item.id;
        warehouseId.value = item.warehouse_id;
        warehouseName.value = item.title;
    }
 
    open.value = true;
    getLossSettingList();
    getProductList();

};

// 确认操作
const handleConfirm = async () => {
    console.log('保存前的原始数据:', lossData.value);
    
    // 数据验证
    const validItems = lossData.value.filter(item => {
        return item.spu_id && item.consume_num >= 0;
    });
    
    if (validItems.length === 0) {
        ElMessage.warning('请至少添加一个有效的损耗设置项');
        return;
    }
    
    // 格式化数据以匹配API要求
    const warehouse_serve_items = validItems.map(item => ({
        warehouse_id: String(warehouseId.value),
        service_id: String(warehouseServeId.value),
        service_name: String(warehouseName.value),
        spu_id: String(item.spu_id),
        spu_name: String(item.spu_name || ''),
        measure_unit_id: String(item.measure_unit_id || ''),
        consume_num: Number(item.consume_num).toFixed(2) // 格式化为两位小数的字符串
    }));
    
    const requestData = {
        // warehouse_serve_id: String(warehouseServeId.value),
        warehouse_serve_items: warehouse_serve_items
    };
    

    try {
        const res = await api.consumablesSettings.saveconsumablesSettings(requestData);
        
        console.log('保存结果:', res);
        
        if (res.code === 200) {
            ElMessage.success('损耗设置保存成功');
            open.value = false;
            emit('init'); // 通知父组件刷新数据
        } else {
            ElMessage.error(res.message || '保存失败，请重试');
        }
    } catch (error) {
        console.error('保存损耗设置时发生错误:', error);
        ElMessage.error('保存失败，请重试');
    }
};



defineExpose({
    openDialog
});
</script>

<style lang="scss" scoped>
.loss-setting-container {
    .table-container {
        .loss-input-group {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;

            .el-button {
                width: 24px;
                height: 24px;
                min-height: 24px;
                padding: 0;
                border-radius: 2px;
            }

            .el-input {
                :deep(.el-input__inner) {
                    text-align: center;
                    padding: 0 5px;
                }
            }
        }

        .add-item-container {
            margin-top: 15px;
            text-align: left;

            .el-button {
                color: #409eff;
                font-size: 14px;
            }
        }
    }
}

:deep(.el-dialog) {
    .el-dialog__header {
        padding: 15px 20px;
        border-bottom: 1px solid #e4e7ed;

        .el-dialog__title {
            font-size: 16px;
            font-weight: 500;
        }
    }

    .el-dialog__body {
        padding: 20px;
    }

    .el-dialog__footer {
        padding: 15px 20px;
        border-top: 1px solid #e4e7ed;
    }
}

:deep(.el-table) {
    .el-table__header {
        th {
            background-color: #f5f7fa;
            color: #606266;
            font-weight: 500;
        }
    }

    .el-table__body {
        .el-table__row {
            &:hover {
                background-color: #f5f7fa;
            }
        }
    }
}

:deep(.el-select) {
    .el-input {
        .el-input__inner {
            border: 1px solid #dcdfe6;
            border-radius: 4px;
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
